package org.example.Interceptors;

import lombok.extern.slf4j.Slf4j;
import org.example.common.ApiResponse;
import org.example.common.TokenStorage;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description
 * @Author 魏锴
 * @Date 2023/12/8
 */

@Slf4j
public class loginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //此处判断session会话当中是否存在username
        System.out.println();
        System.out.println("连接: " + request.getMethod() + "  " + request.getRequestURI());
        if ("OPTIONS".equals(request.getMethod())) {//检测是options方法则直接返回200
            response.setStatus(HttpStatus.OK.value());
            return true;
        }
        System.out.println("<------ 登录检查开始 ------>");
        String token = request.getHeader("token");
        TokenStorage.setToken(token);
        Object obj = request.getSession().getAttribute(token);
        if (obj != null) {
            System.out.println("<------ 登录检查成功 ------>");
            return true;
        }
        System.out.println("<------ 登录检查失败 ------>");
        ApiResponse.returnDataDirectly(response, ApiResponse.certificationExpires());
        return false;
    }

}
